import axios from "axios";
import api from "../../api/api";
import { ElMessage, ElMessageBox } from "element-plus";
export function download(data, titName) {
  if (!data) {
    return;
  }
  const content = data;
  const blob = new Blob([content], { type: "application/vnd.ms-excel" });
  const fileName = titName ? titName : "报废卡号.xlsx";
  if ("download" in document.createElement("a")) {
    // 非IE下载
    const elink = document.createElement("a");
    elink.download = fileName;
    elink.style.display = "none";
    elink.href = URL.createObjectURL(blob);
    document.body.appendChild(elink);
    elink.click();
    URL.revokeObjectURL(elink.href); // 释放URL 对象
    document.body.removeChild(elink);
  } else {
    // IE10+下载
    navigator.msSaveBlob(blob, fileName);
  }
}
// 模板下载
export function getdownload(code) {
  return new Promise(function (resolve, reject) {
    axios({
      method: "GET",
      url: api.getUrl() + "backup/excel/download?code=" + code,
      responseType: "blob",
    })
      .then((resdata) => {
        resolve(resdata.data);
      })
      .catch((err) => {
        if (!handleError(err.response)) {
          error(err);
        }
      });
  });
}
// 文件导入
export function ToLeadfunction(form) {
  let timer = "";
  let timerNumber = 0;
  let token = localStorage.getItem("token");
  return new Promise(function (resolve, reject) {
    axios({
      method: "post",
      url: api.getUrl() + "backup/excel/upload",
      data: form,
      headers: {
        "Content-Type": "multipart/form-data",
        Authorization: "Bearer " + token,
      },
    })
      .then((resdata) => {
        if (resdata.data.code == 1) {
          timer = setInterval(function () {
            timerNumber++;
            api
              .getListAPI("backup/excel/process", {
                code: resdata.data.data,
              })
              .then((res) => {
                if (res.data.code == 2) {
                  ElMessage.success(res.data.message);
                  resolve(resdata.data);
                  clearInterval(timer);
                } else {
                  if (timerNumber > 5) {
                    clearInterval(timer);
                  }
                  ElMessage.error(res.data.message);
                }
              })
              .catch((err) => {
                if (timerNumber > 5) {
                  clearInterval(timer);
                }
              });
          }, 2000);
        } else {
          clearInterval(timer);
          ElMessage.error(resdata.data.message);
        }
      })
      .catch((err) => {
        ElMessage.error(resdata.data.message);
      });
  });
}